package com.service.other;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 将Gps数据读入缓存和数据库中
 * @author sxc
 *
 */
public class Reader {

	
	/**
	 * 读指定文件中的最后一条数据
	 * @param path 指定文件地址
	 * @param charset 字符集
	 * @return 最后一条数据 String
	 */
	public static String readLastLine(String path, String charset){
		String text = null;
		try{
			File file = new File(path);
			if (!file.exists() || file.isDirectory() || !file.canRead()) {
				text = null;
			}
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			long len = raf.length();
			if(len == 0L){
				text = null;
			}else{
				long pos = len - 1;
				while (pos > 0) {
					pos--;
					raf.seek(pos);
					if (raf.readByte() == '\n') {
						break;
					}
				}
				if(pos == 0){
					raf.seek(0);
				}
				byte[] bytes = new byte[(int)(len - pos-3)];
				raf.read(bytes);
				raf.close();
				if(charset == null){
					text = new String(bytes).replace("\r\n", "");
				}else{
					text = new String(bytes, charset).replace("\r\n", "");
				}
			}
		}catch(IOException e){
			e.printStackTrace();
		}
		return text;
	}
}
